﻿using System;
using System.IO;

namespace AcceptanceTests
{
    // Inspiration for implementation came from the following:
    // http://stackoverflow.com/questions/4884043/how-to-write-to-console-out-during-execution-of-an-mstest-test
    internal class ConsoleRedirector : IDisposable
    {
        private readonly StringWriter _consoleOutput = new StringWriter();
        private readonly TextWriter _originalConsoleOutput;
        private readonly bool _writeToOriginalConsoleOutput;

        public ConsoleRedirector(bool writeToOriginalConsoleOutput)
        {
            _writeToOriginalConsoleOutput = writeToOriginalConsoleOutput;
            _originalConsoleOutput = Console.Out;
            Console.SetOut(_consoleOutput);
        }

        public void Dispose()
        {
            Console.SetOut(_originalConsoleOutput);
            if (_writeToOriginalConsoleOutput)
                Console.Write(ToString());
            _consoleOutput.Dispose();
        }

        public override string ToString()
        {
            return _consoleOutput.ToString();
        }
    }
}